﻿using System;
using System.Web;
using System.IO;

namespace HelpersDotNet.Web
{
    public static partial class WebHelper
    {
        /// <summary>
        /// Terminates the current application. The application restart the next time a request is recieved for it.<br/>
        /// Requires either Full Trust or write access to web.config.
        /// </summary>
        /// <returns></returns>
        public static bool RestartWebApplication()
        {
            bool error = false;

            try
            {
                // This requires full trust which is most likely to fail in many scenarios.
                HttpRuntime.UnloadAppDomain();
            }
            catch
            {
                error = true;
            }

            if (!error)
                return true;

            // Couldn't unload with runtime. Let's try modifying web.config
            try
            {
                File.SetLastWriteTimeUtc(
                    HttpContext.Current.Request.ApplicationPath + "\\web.config", DateTime.UtcNow);
            }
            catch
            {
                return false;
            }
            return true;
        }

    }
}